<template>
  <div class="ChatWith">
    <header_part :title="route.query.userName" :xiao="xiao" @goback="goback" />
    <div class="scrollY" ref="scrollY">
      <div class="chat" v-for="item, index in GetPrivateArr" :key="index">
        <div class="chanItem" ref="chanItem">
          <p>{{ diaplayTime(item.createdAt) }}</p>
          <!-- 自己 -->
          <div class="msg-right" v-show="item.fromId === myId">
            <span>{{ item.privateLetterContent }}</span>
            <div class="right"></div>
            <img :src="`http://43.138.15.137:3000${myAvatar}`" alt="">
          </div>
          <!-- 对方 -->
          <div class="msg-left" v-show="item.fromId === userId">
            <img :src="`http://43.138.15.137:3000${route.query.userAvatar}`" alt="">
            <div class="left"></div>
            <span>{{ item.privateLetterContent }}</span>
          </div>
        </div>
      </div>
    </div>
    <ComponentBottom_part @ok="ok" :placeholderval="placeholderval" />
  </div>
</template>


<script setup>
import { ref, inject, onMounted, onUpdated } from 'vue'
// 头部组件
import header_part from '../components/common/header-part.vue'
// 底部组件
import ComponentBottom_part from '../components/common/ComponentBottom-part.vue';
import { useRoute } from 'vue-router'
const route = useRoute()
// 聊天对象id
const userId = route.query.userId
// 自己id
const myId = JSON.parse(localStorage.getItem('data')).userId
// 自己得头像
const myAvatar = JSON.parse(localStorage.getItem('data')).userAvatar
// input框的placeholderval
const placeholderval = ref('发送信息...')
// 控制返回按钮显示隐藏
const xiao = ref(true)
// 聊天盒子DOM
const scrollY = ref(null)
// 聊天信息数组
const GetPrivateArr = ref([])
// 读取信息数组
const ReadPrivateArr = ref([])
import { getGetPrivateLetterAPI, getReadPrivateLetterAPI, postPrivateLetterAPI } from '../api/ChatWidth-page'
const socket = inject("socket"); // 注入到全局
socket.emit('login', myId) // 把用户id传递后端，后端把用户id和socketId关联；login客户端和服务端协商好的事件


// DOM元素加载完调用
onMounted(() => {
  scrollToBottom()
})

// 视图更新的时候调用
onUpdated(() => {
  scrollToBottom()
})
GetPrivate()
async function GetPrivate() {
  console.log(userId, '聊天对象id', myId, '自己id');
  let GetPrivateRes = await getGetPrivateLetterAPI(myId, userId)
  GetPrivateArr.value = GetPrivateRes.data.data
  console.log(GetPrivateArr.value, '获取聊天');
}
ReadPrivate()
async function ReadPrivate() {
  let ReadPrivateRes = await getReadPrivateLetterAPI(myId, userId)
  ReadPrivateArr.value = ReadPrivateRes.data.data
  console.log(ReadPrivateArr.value, '读取聊天');
}
// 返回按钮
async function goback() {
  window.history.go(-1)
}

// 发送数据到服务端
async function ok(val) {
  // console.log(val);
  let obj = {
    content: val,
    fromUserId: myId,
    toUserId: userId
  }
  let postPrivateRes = await postPrivateLetterAPI(myId, userId, obj)
  let obj1 = {
    fromId: myId, //我的id
    toId: userId, //对方id
    privateLetterContent: val, //内容
    createdAt: Date.now(),
    userAvatar: `/assets/avatar/${myId}.png`,
    userNickname: JSON.parse(localStorage.getItem('data')).userNickname //名字
  }
  if (postPrivateRes.data.code === 200) {
    socket.emit('sendPrivateLetter', obj1)
    val = ''
    GetPrivate()
    ReadPrivate()
  }
  console.log(postPrivateRes);
}

socket.on('receivePrivateLetter', data => { // receivePrivateLetter客户端和服务端协商好的事件
  GetPrivateArr.value.push(data)
})

// 当DOM更新即滚动到最底部
function scrollToBottom() {
  // 将盒子的高度赋值给滚动的高度
  scrollY.value.scrollTop = scrollY.value.scrollHeight
}



function diaplayTime(data) {
  //将字符串转换成时间格式
  // 发送时间
  let timePublish = new Date(data);
  // 现在时间
  let timeNow = new Date();
  // 1分钟
  let minute = 1000 * 60;
  let minute3 = 3000 * 60;
  console.log(minute3);
  // 1小时
  let hour = minute * 60;
  // 1天
  let day = hour * 24;
  // 1个月
  let month = day * 30;
  // 1年
  let year = month * 12;
  // 距离发送时的时间=现在时间-发送时间
  let diffValue = timeNow - timePublish;
  console.log(diffValue, '距离发送时的时间');
  let diffMonth = diffValue / month;
  let diffWeek = diffValue / (7 * day);
  let diffDay = diffValue / day;
  let diffHour = diffValue / hour;
  let diffMinute = Math.floor(diffValue / minute);
  // let diffMinute = diffValue / minute;
  let diffYear = diffValue / year;
  let result = ''
  if (diffValue < minute) {
    result = "刚刚";
  } else if (diffYear > 1) {
    result = Math.floor(diffYear) + "年前";
  } else if (diffMonth > 1) {
    result = Math.floor(diffMonth) + "月前";
  } else if (diffWeek > 1) {
    result = Math.floor(diffWeek) + "周前";
  } else if (diffDay > 1) {
    result = Math.floor(diffDay) + "天前";
  } else if (diffHour > 1) {
    result = Math.floor(diffHour) + "小时前";
  } else if (diffMinute > 1) {
    result = Math.floor(diffMinute) + "分钟前";
  } else {
    result = "";
  }
  return result;
}
</script>



<style lang="scss" scoped>
.scrollY {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin-top: 45px;
  margin-bottom: 40px;
  background: #161622;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }
}

.chat {
  p {
    color: white;
    text-align: center;
    font-size: 10px;
    line-height: 10px;
  }

  div {
    position: relative;
    color: #000;
    font-size: 14px;

    img {
      margin-left: 15px;
      margin-right: 15px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      vertical-align: middle;
    }

    .right {
      position: absolute;
      top: 4px;
      right: 63px;
      width: 0;
      height: 0;
      border-left: 15px solid #86ec56;
      border-top: 14px solid transparent;
      border-bottom: 14px solid transparent;
    }

    .left {
      position: absolute;
      top: 4px;
      left: 63px;
      width: 0;
      height: 0;
      border-right: 15px solid #fff;
      border-top: 14px solid transparent;
      border-bottom: 14px solid transparent;
    }

    span {
      padding: 5px 10px;
      border-radius: 5px;
    }

  }

  .msg-right {
    text-align: right;
  }

  .msg-right span {
    background: #86ec56;
  }

  .msg-left {
    text-align: left;
  }

  .msg-left span {
    background: white;
  }
}

.input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #1A1B20;
  line-height: 44px;
  z-index: 99;
  display: flex;

  input {
    flex: 1;
    font-size: 14px;
    color: #e8e8e9;
    padding-left: 10px;
    caret-color: #face15;
    background: #1a1b20;
  }



  span {
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    width: 44px;
    color: #fff;
  }
}
</style>